import {EventSource} from 'eventsource'
import http from "@/axios/http";

class SseClient {
  constructor() {
    this.eventSource = null;
  }

  sessionId = null
  eventSource = null

  /**
   * 注册SSE并直接注册消息和错误回调
   * @param {string} url
   * @param {function} onMessage
   * @param {function} onError
   */
  registerSse(onMessage, onError) {
    if (this.eventSource) {
      this.eventSource.close();
    }
    // 使用 eventsource 包时可传 headers
    this.eventSource = new EventSource(process.env.VUE_APP_BASE_API + 'sse/register', {
      fetch: (input, init) =>
        fetch(input, {
          ...init,
          headers: {
            ...init.headers,
            token: `${localStorage.getItem("token")}`
          },
        }),
    });
    console.log(onMessage, onError);

    // 监听连接打开事件
    this.eventSource.addEventListener('init', (e) => {
      console.log('SSE connection initialized', e);
      this.sessionId = e.data; // 获取sessionId
      console.log('SSE session initialized with ID:', this.sessionId);
    });

    // 监听错误事件
    this.eventSource.addEventListener('error', (err) => {
      console.log('SSE error event:', err);
      if (typeof onError === 'function') {
        onError(err);
      }
    })

    // 监听消息事件
    this.eventSource.addEventListener('message', (event) => {
      console.log('SSE message event:', event);
        if (typeof onMessage === 'function') {
          onMessage(event);
        }
    })
    this.eventSource.addEventListener('complete', (event) => {
      console.log('SSE complete event:', event);
        if (typeof onMessage === 'function') {
          onMessage(event);
        }
    })

    // 监听连接打开事件
    this.eventSource.addEventListener('open', (e) => {
      console.log('SSE connection opened', e);
    });

  }

  /**
   * 发送消息
   * @param {any} message
   */
  async sendMessage(data) {
    return http.post(`sse/chat`, {
      ...data,
      sessionId: this.sessionId
    })
  }

  /**
   * 上传图片（直接处理base64格式）
   * @param {string} base64Str
   */
  async uploadImage(base64Str) {
    return http.post('sse/upload-image', {
      imgBase64: base64Str,
      sessionId: this.sessionId
    });
  }
}

export default SseClient

